#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from xpy3lib.utils import db_utils as util
from xpy3lib.LoggableObject import LoggableObject


class XRetryableQuery(LoggableObject):
    db_conn = None
    sql = None
    max_times = -1

    def __init__(self, p_db_conn=None, p_sql=None, p_max_times=1):
        super(XRetryableQuery, self).__init__()
        self.db_conn = p_db_conn
        self.sql = p_sql
        self.max_times = p_max_times
        self.__times = -1

    def redo(self):
        df = None
        try:
            self.__times += 1
            if self.__times < self.max_times:
                df = util.query(conn=self.db_conn, sql=self.sql)
        except Exception as e:
            self.logger.error(str(e))
            df = self.redo()
        return df
